<template>
  <v-content ref="content" single flex padding-top="30" background="#ffad01">
        <v-statusbar class="status-bar"></v-statusbar>

    <div class="header padding">
      <div class="item back-btn" @click="onBack">
        <image class="image" src="/static/image/exam/icon-back.png"></image>退出练习
      </div>
      <div class="item">
        <div class="number">{{ current }}/{{ questionLength }}</div>
      </div>
    </div>

    <div class="main padding">
      <div class="number indicator">
        <div class="span">{{ current }}</div>
        /{{ questionLength }}
      </div>

      <!-- 直接在页面中实现题目渲染，不使用TestQuestion组件 -->
      <div v-if="nowQuestion.title" class="question-container">
        <div class="question">
          <div class="title">
            {{ nowQuestion.title }}
          </div>
          <div class="text-question">
            <div class="options-grid">
              <div class="item" :class="{
                active: userAnswer !== '' && userAnswer == index,
                correct: userAnswer !== '' && index == nowQuestion.correctAnswer,
                wrong: userAnswer !== '' && userAnswer == index && index != nowQuestion.correctAnswer
              }" v-for="(item, index) in answerList" :key="index" @click="onOptionClick(index)">
                <div class="number">{{ index }}</div>
                <div class="option-text">{{ item }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 当没有题目时显示加载提示 -->
      <div v-else class="loading-container">
        <text>正在生成中，请耐心等待...</text>
      </div>

      <!-- 答案反馈区域 -->
      <div v-if="feedbackType" class="feedback-section">
        <div :class="['feedback', feedbackType]">
          <uni-icons :type="feedbackIcon" size="30" :color="feedbackcolor"></uni-icons>
          <span class="feedback-text">{{ feedbackText }}</span>
        </div>
        <div v-if="feedbackType === 'wrong'" class="analysis-button-container">
          <button class="analysis-button" @click="showAnalysisPopup">查看AI解析</button>
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="button" key="next" @click="onFinish" v-if="current == questionLength">完成练习</div>
      <div class="button" key="end" @click="toNext" v-else>下一题</div>
    </div>

    <!-- AI解析弹窗 -->
    <v-popup ref="analysisPopup" type="bottom" round round-size="20" :closeable="true">
      <div class="analysis-popup-content">
        <div class="analysis-title">
          <text>AI解析</text>
        </div>
        <div class="analysis-content">
          <!-- 这里不再需要ai-robot组件，因为它已经常驻显示在页面上 -->
          <text v-if="nowQuestion.explanation">{{ nowQuestion.explanation }}</text>
          <text v-else>ai正在生成中，请耐心等待...</text>
        </div>
      </div>
    </v-popup>

    <!-- 将ai-robot组件移出弹窗，使其常驻显示在页面上 -->
    <ai-robot :question="nowQuestion"></ai-robot>
  </v-content>
</template>

<script>
import mixins from "@/mixins"
import aiRobot from "@/components/ai-robot/index.vue"

export default {
  name: "practice",
  mixins: [mixins],
  data() {
    return {
      feedbackType: '', // 'correct' 或 'wrong'
      feedbackText: '',
      feedbackIcon: '',
      feedbackcolor: '',
      questionInfo: {},//题目数据
      questionList: [],//题目列表
      currentIndex: 0, // 当前题目索引
      userAnswer: "", // 用户的答案
      answerList: [],
    }
  },
  computed: {
    questionLength() {
      return this.questionList.length
    },
    current: {
      get() {
        return this.currentIndex + 1
      },
      set(value) {
        this.currentIndex = value - 1
        setTimeout(() => {
          this.resetFeedback()
        }, 100)
      },
    },
    nowQuestion() {
      if (!this.questionList[this.currentIndex]) return {}

      // 转换题目格式
      const question = this.questionList[this.currentIndex]
      const formattedQuestion = {
        title: question.question,
        score: 10,
        correctAnswer: question.correctAnswer,
        explanation: question.explanation,
        options: question.options,
      }
      return formattedQuestion
    },

  },
  methods: {
    onBack() {
      this.showMessage.modal({
        title: "提示",
        content: "退出将会中断练习, 确认退出吗 ?",
        confirm: next => {
          next()
          this.toPage(-1)
        },
      })
      return true
    },

    toNext() {
      if (this.current >= this.questionLength) {
        return
      }
      this.current++
    },

    // 修改onOptionClick方法，使用userAnswer存储答案
    // 选项点击处理 - 简化为只处理单选题
    onOptionClick(index) {
      // 已经选择过答案则不再允许修改
      if (this.userAnswer !== "") {
        return;
      }

      const userAnswer = index
      const correctAnswer = this.nowQuestion.correctAnswer

      // 保存用户的选择
      this.userAnswer = userAnswer

      // 设置反馈信息
      if (userAnswer === correctAnswer) {
        this.feedbackType = 'correct'
        this.feedbackText = '回答正确！'
        this.feedbackIcon = "checkbox-filled"
        this.feedbackcolor = "#52c41a" // 改为浅绿色
      } else {
        this.feedbackType = 'wrong'
        this.feedbackText = '回答错误，请查看解析'
        this.feedbackIcon = "clear"
        this.feedbackcolor = "#ff0000"
      }
    },

    resetFeedback() {
      this.feedbackType = ''
      this.feedbackText = ''
      this.feedbackIcon = ''
      this.feedbackcolor = ''
      this.userAnswer = "" // 重置用户的选择
    },
    getAnswerList() {
      if (!this.nowQuestion) return
      return this.nowQuestion.options
    },
    showAnalysisPopup() {
      this.$refs.analysisPopup.show()
    },

    onFinish() {
      this.showMessage.modal({
        title: "练习完成",
        content: "恭喜您完成所有练习题目！",
        showCancel: false,
        confirm: next => {
          next()
          this.toPage(-1)
        },
      })
    },
  },
  components: {
    aiRobot
  },
  // 修改mounted方法
  async mounted() {
    this.questionInfo = this.query;
    try {
      // 等待异步请求完成
      const response = await this.$axios.post('/ai/generate/question/course', this.questionInfo);
      // 从响应中获取数据
      if (response) {
        this.questionList = response;
        this.answerList = this.getAnswerList()
      } else {
        console.error('获取题目失败:', response.data?.msg || '未知错误');
        // 题目获取失败，提示用户并返回上一页
        this.showMessage.toast('获取题目失败，请检查网络设置');
        setTimeout(() => {
          this.toPage(-1);
        }, 1500);
      }
    } catch (error) {
      console.error('请求异常:', error);
      setTimeout(() => {
        this.toPage(-1);
      }, 1500);
    }
  }
}
</script>

<style lang="scss" scoped>
.header {
  color: #333;
  padding-bottom: 20rpx;
  // 添加flex布局使元素合理分布
  display: flex;
  justify-content: space-between;
  align-items: center;

  .item {
    font-size: 28rpx;
    font-weight: 500;
    padding-bottom: 14rpx;

    .image {
      width: 27rpx;
      height: 34rpx;
      margin-right: 10rpx;
      filter: brightness(0.7);
    }
  }

  .back-btn {
    position: relative;
    transition: all 0.3s ease;
    width: 200rpx;
    padding: 10rpx 20rpx;
    border-radius: 20rpx;
    background: rgba(255, 255, 255, 0.8);
    border: 1rpx solid #ddd;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    text-align: center;

    &:hover {
      background: rgba(255, 255, 255, 0.95);
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    }
  }

  .number {
    margin-left: auto;
    color: #333;
    background: rgba(255, 255, 255, 0.8);
    padding: 6rpx 20rpx;
    border-radius: 20rpx;
    font-weight: bold;
    border: 1rpx solid #ddd;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
  }
}

.main {
  height: 100%;
  background: #fff;
  border-radius: 50rpx 50rpx 0 0;
  padding-top: 60rpx;
  margin-top: 20rpx;
  overflow: auto;
  padding-bottom: 200rpx;
  box-shadow: 0 -5rpx 20rpx rgba(0, 0, 0, 0.1);

  .indicator {
    color: #808281;
    font-size: 31rpx;
    padding-bottom: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 40rpx;

    .span {
      color: $color;
      font-size: 160%;
      display: inline-block;
      vertical-align: -5rpx;
      font-weight: bold;
    }
  }

  .question-container {
    padding-bottom: 40rpx;
  }

  // 题目样式
  .question {
    .title {
      font-size: 31rpx;
      padding-bottom: 50rpx;

      .tip {
        color: #9d9d9d;
      }
    }
  }

  // 文本题目样式
  .text-question {
    // 为选项容器添加内边距，确保选项不会紧贴边缘
    padding: 20rpx 0;
  }

  // 选项网格布局
  .options-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(45%, 1fr));
    grid-gap: 20rpx;
  }

  // 选项样式
  .options-grid .item {
    font-size: 30rpx;
    padding: 24rpx 30rpx;
    margin: 10rpx 0;
    border-radius: 40rpx; // 较大的圆角形成胶囊形状
    border: 2px solid #e0e0e0;
    background-color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    min-height: 120rpx;
    position: relative;
    overflow: hidden;

    // 确保内容在波纹效果之上
    .number,
    .option-text {
      position: relative;
      z-index: 1;
    }

    // 优化点击效果
    &:not(.readonly):active {
      transform: translateY(0) scale(0.97);
      box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }

    // 选项中的字母标识
    .number {
      font-weight: bold;
      margin-right: 16rpx;
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
    }

    // 选项文本
    .option-text {
      flex: 1;
      word-break: break-word;
      line-height: 1.5;
    }

    // 选中状态
    &.active {
      color: #fff;
      border-color: $color;
      background-color: $color;
      box-shadow: 0 4rpx 16rpx rgba(255, 173, 1, 0.3);

      .number {
        color: $color;
        background-color: #fff;
      }
    }

    // 正确答案状态（浅绿色）
    &.correct {
      color: #fff;
      border-color: #52c41a;
      background-color: #52c41a;
      box-shadow: 0 4rpx 16rpx rgba(82, 196, 26, 0.3);

      .number {
        color: #52c41a;
        background-color: #fff;
      }
    }

    // 错误答案状态（红色）
    &.wrong {
      color: #fff;
      border-color: #ff0000;
      background-color: #ff0000;
      box-shadow: 0 4rpx 16rpx rgba(255, 0, 0, 0.3);

      .number {
        color: #ff0000;
        background-color: #fff;
      }
    }
  }

  // 删除只读状态样式
  .readonly {
    cursor: not-allowed;
    opacity: 0.8;
  }

  // 加载提示样式
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;
    color: #999;
    font-size: 32rpx;
  }

  // 答案反馈区域样式
  .feedback-section {
    margin-top: 40rpx;
    padding: 20rpx;
    animation: fadeIn 0.5s ease-out;
  }

  .feedback {
    display: flex;
    align-items: center;
    padding: 25rpx 35rpx;
    border-radius: 20rpx; // 增大圆角
    font-size: 32rpx; // 增大字体
    transition: all 0.3s ease; // 添加过渡效果
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05); // 添加轻微阴影
  }

  .feedback.correct {
    background-color: #f0fff4;
    color: #52c41a;
    border: 1rpx solid #b7eb8f;
  }

  .feedback.wrong {
    background-color: #fef0f0;
    color: #f56c6c;
    border: 1rpx solid #fbc4c4;
  }

  // 优化图标和文字间距
  .feedback-text {
    flex: 1;
    margin-left: 20rpx; // 增加与图标的间距
  }

  // 解析按钮容器
  .analysis-button-container {
    margin-top: 30rpx; // 增加与反馈区域的间距
    display: flex;
    justify-content: center;
  }

  // 解析按钮
  .analysis-button {
    background-color: $color;
    color: #fff;
    border: none;
    padding: 18rpx 50rpx; // 增加内边距
    border-radius: 30rpx;
    font-size: 30rpx; // 增大字体
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 12rpx rgba(255, 173, 1, 0.3);

    &:hover {
      background-color: #ffb727;
      transform: scale(1.05);
      box-shadow: 0 6rpx 16rpx rgba(255, 173, 1, 0.4);
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #f9f9f9;
  color: #959595;
  text-align: center;
  height: 110rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  box-sizing: content-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.05);
  z-index: 10;

  .button {
    width: 100%;
    height: 100%;
    background: transparent;
    box-shadow: none;
    color: inherit;
    display: flex;
    background: #fab214;
    font-weight: 800;
    font-size: 34rpx;
    color: #eee;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

  }

  .answer-card {
    position: absolute;
    width: 140rpx;
    height: 140rpx;
    border-radius: 50%;
    background: $color;
    color: #fff;
    font-size: 24rpx;
    bottom: 20rpx;
    left: 0;
    right: 0;
    margin: auto;
    z-index: 2;
    box-shadow: 0 8rpx 20rpx rgba(255, 173, 1, 0.4);
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 10rpx;

    &:hover {
      transform: scale(1.05);
      box-shadow: 0 12rpx 25rpx rgba(255, 173, 1, 0.5);
    }

    &:active {
      transform: scale(0.95);
    }

    .image {
      width: 42rpx;
      height: 42rpx;
      display: block;
      margin-bottom: 8rpx;
    }
  }
}

.popup-answer-card {
  padding-inline: 20rpx;
  padding-bottom: 50rpx;
}

// AI解析弹窗样式
.analysis-popup-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;

  .analysis-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 20rpx;
  }

  .analysis-content {
    min-height: 400rpx;
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.main {
  animation: fadeIn 0.3s ease-out;
}
</style>